﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor.Android;
using UnityEngine;

namespace XUBugly
{
    namespace Editor
    {
        internal class BuglyPostAndroidProject : IPostGenerateGradleAndroidProject
        {
            public int callbackOrder
            {
                get
                {
                    return 999;
                }
            }

            void IPostGenerateGradleAndroidProject.OnPostGenerateGradleAndroidProject(string path)
            {
                Debug.Log("XUBugly Bulid path : " + path);

                //支持AndroidX
                //{
                //    string gradlePropertiesFile = (new DirectoryInfo(path)).Parent.FullName + "/gradle.properties";
                //    List<string> allLine = new List<string>(File.ReadAllLines(gradlePropertiesFile));
                //    bool replaceAndroidX = false;
                //    bool replaceJetifier = false;
                //    for (int i = 0; i < allLine.Count; i++)
                //    {
                //        if (allLine[i].StartsWith("android.useAndroidX"))
                //        {
                //            allLine[i] = "android.useAndroidX=true";
                //            replaceAndroidX = true;
                //        }
                //        if (allLine[i].StartsWith("android.enableJetifier"))
                //        {
                //            allLine[i] = "android.enableJetifier=true";
                //            replaceJetifier = true;
                //        }
                //    }
                //    if (!replaceAndroidX)
                //    {
                //        allLine.Add("android.useAndroidX=true");
                //    }
                //    if (!replaceJetifier)
                //    {
                //        allLine.Add("android.enableJetifier=true");
                //    }
                //    File.WriteAllLines(gradlePropertiesFile, allLine);
                //}
                //{
                //    string gradleSettingPath = path + "/build.gradle";
                //    string allText = File.ReadAllText(gradleSettingPath);
                //    if (allText.Contains("androidx.appcompat:appcompat") == false)
                //    {
                //        List<string> allLine = new List<string>(File.ReadAllLines(gradleSettingPath));
                //        for (int i = 0; i < allLine.Count; i++)
                //        {
                //            if (allLine[i].Contains("implementation"))
                //            {
                //                allLine.Insert(i + 1, "    implementation 'androidx.appcompat:appcompat:1.2.0'");
                //                break;
                //            }
                //        }
                //        File.WriteAllLines(gradleSettingPath, allLine);
                //    }
                //}

                //Bugly权限申请
                {
                    for (int i = 0; i < 2; i++)
                    {
                        string manifestFile;
                        if (i == 0)
                        {
                            manifestFile = path + "/src/main/AndroidManifest.xml";
                        }
                        else
                        {
                            manifestFile = (new DirectoryInfo(path)).Parent.FullName + "/launcher/src/main/AndroidManifest.xml";
                        }
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(manifestFile);
                        XmlNode xnRoot = xmlDoc.SelectSingleNode("manifest");
                        XmlNodeList xnPermissions = xnRoot.SelectNodes("uses-permission");

                        Dictionary<string, bool> permissionMap = new Dictionary<string, bool>()
                        {
                            {"android.permission.READ_PHONE_STATE", false },
                            {"android.permission.INTERNET", false },
                            {"android.permission.ACCESS_NETWORK_STATE", false },
                            {"android.permission.ACCESS_WIFI_STATE", false },
                            {"android.permission.READ_LOGS", false },
                        };

                        for (int j = 0; j < xnPermissions.Count; j++)
                        {
                            XmlElement xnPermission = (XmlElement)xnPermissions.Item(j);
                            string permission = xnPermission.GetAttribute("android:name");
                            if (permissionMap.ContainsKey(permission))
                            {
                                permissionMap[permission] = true;
                            }
                        }

                        foreach (var permission in permissionMap)
                        {
                            if (permission.Value == false)
                            {
                                XmlNode xnLast = xnPermissions.Count > 0 ? xnPermissions.Item(xnPermissions.Count - 1) : null;
                                XmlElement xnPermission = xmlDoc.CreateElement("uses-permission");
                                xnPermission.SetAttribute("name", "http://schemas.android.com/apk/res/android", permission.Key);
                                if (permission.Key == "android.permission.READ_LOGS")
                                {
                                    xnPermission.SetAttribute("ignore", "http://schemas.android.com/tools", "ProtectedPermissions");
                                }
                                if (xnLast != null)
                                {
                                    xnRoot.InsertAfter(xnPermission, xnLast);
                                }
                                else
                                {
                                    xnRoot.AppendChild(xnPermission);
                                }
                            }
                        }

                        XmlElement xnApp = (XmlElement)xnRoot.SelectSingleNode("application");
                        if (!xnApp.HasAttribute("usesCleartextTraffic", "http://schemas.android.com/apk/res/android"))
                        {
                            xnApp.SetAttribute("usesCleartextTraffic", "http://schemas.android.com/apk/res/android", "true");
                        }

                        xmlDoc.Save(manifestFile);
                    }
                }

                //gradle集成
                {
                    string gradleSettingPath = path + "/build.gradle";
                    List<string> gradleSettingLines = new List<string>(File.ReadAllLines(gradleSettingPath));
                    for (int i = 0; i < gradleSettingLines.Count; i++)
                    {
                        if (gradleSettingLines[i].Trim().StartsWith("implementation"))
                        {
                            gradleSettingLines.Insert(i, "\tcompile 'com.tencent.bugly:nativecrashreport:latest.release'");
                            gradleSettingLines.Insert(i, "\tcompile 'com.tencent.bugly:crashreport:latest.release'");
                            break;
                        }
                    }
                    File.WriteAllLines(gradleSettingPath, gradleSettingLines.ToArray());
                }

                BuglySymbolsUpload.UploadBuglyso();
            }
        }
    }
}